# -*- coding: utf-8 -*-
# @Time    : 2024/12/20
# @Author  : Assistant
# @File    : LuckDbInitHelperUtils.py
# @Describe: 数据库初始化工具类

import os
import sqlite3
import shutil
import logging
from luck.core.LuckConstant import LuckConstant

class LuckDbInitHelperUtils:
    """数据库初始化工具类"""
    
    @staticmethod
    def init_database():
        """初始化数据库，确保数据库文件存在"""
        try:
            db_path = LuckConstant.get_db_path()
            
            # 如果数据库文件不存在，需要创建
            if not os.path.exists(db_path):
                logging.info(f"数据库文件不存在，开始初始化: {db_path}")
                
                # 确保目录存在
                db_dir = os.path.dirname(db_path)
                if not os.path.exists(db_dir):
                    os.makedirs(db_dir, exist_ok=True)
                    logging.info(f"创建数据库目录: {db_dir}")
                
                # 尝试从原始位置复制数据库文件
                original_db_path = LuckDbInitHelperUtils._get_original_db_path()
                if original_db_path and os.path.exists(original_db_path):
                    shutil.copy2(original_db_path, db_path)
                    logging.info(f"从原始位置复制数据库文件: {original_db_path} -> {db_path}")
                else:
                    # 创建新的数据库文件
                    LuckDbInitHelperUtils._create_new_database(db_path)
                    logging.info(f"创建新的数据库文件: {db_path}")
            else:
                logging.info(f"数据库文件已存在: {db_path}")
                
            return True
            
        except Exception as e:
            logging.error(f"数据库初始化失败: {e}")
            return False
    
    @staticmethod
    def _get_original_db_path():
        """获取原始数据库文件路径"""
        try:
            # 获取当前脚本目录
            current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            original_db_path = os.path.join(current_dir, LuckConstant.DB_DIR, LuckConstant.DB_NAME)
            return original_db_path
        except Exception:
            return None
    
    @staticmethod
    def _create_new_database(db_path):
        """创建新的数据库文件并初始化表结构"""
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        try:
            # 创建用户表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS sms_users (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    loginid TEXT UNIQUE NOT NULL,
                    username TEXT NOT NULL,
                    password TEXT NOT NULL,
                    email TEXT,
                    phone TEXT,
                    status INTEGER DEFAULT 1,
                    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    update_time DATETIME DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # 创建短信提供商表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS sms_providers (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    code TEXT UNIQUE NOT NULL,
                    config TEXT,
                    status INTEGER DEFAULT 1,
                    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    update_time DATETIME DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # 创建短信模板表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS sms_templates (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    content TEXT NOT NULL,
                    type INTEGER DEFAULT 1,
                    status INTEGER DEFAULT 1,
                    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    update_time DATETIME DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # 创建短信接口表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS sms_interfaces (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    url TEXT NOT NULL,
                    method TEXT DEFAULT 'POST',
                    headers TEXT,
                    params TEXT,
                    status INTEGER DEFAULT 1,
                    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    update_time DATETIME DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # 创建短信记录表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS sms_records (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    phone TEXT NOT NULL,
                    content TEXT NOT NULL,
                    provider_id INTEGER,
                    template_id INTEGER,
                    status INTEGER DEFAULT 0,
                    send_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    response TEXT,
                    error_msg TEXT
                )
            ''')
            
            # 插入默认管理员用户
            cursor.execute('''
                INSERT OR IGNORE INTO sms_users (loginid, username, password, email, status)
                VALUES ('admin', '管理员', '21232f297a57a5a743894a0e4a801fc3', 'admin@example.com', 1)
            ''')
            
            conn.commit()
            logging.info("数据库表结构创建完成")
            
        except Exception as e:
            conn.rollback()
            logging.error(f"创建数据库表结构失败: {e}")
            raise
        finally:
            cursor.close()
            conn.close()